//
//  MainTabBarVC.m
//  ImGuider
//
//  Created by 李陆涛 on 2017/12/11.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "MainTabBarVC.h"
#import "HomePageVC.h"
#import "DestinationVC.h"
#import "MineVC.h"
#import "AllOrderListVC.h"
#import "SelectDestinationVC.h"
#import "IGShare.h"
#import "LinesTabBarItem.h"
#import "CityVC.h"
#import "WebViewVC.h"
#import "LinePreDetailVC.h"
#import "YYCForceUpdateVC.h"
#import <SafariServices/SafariServices.h>
#import <StoreKit/StoreKit.h>
#import "SpecialDetailVC.h"
#import "LoginVC.h"
#import "CityTourListVC.h"

@interface MainTabBarVC () <UITabBarControllerDelegate>

@property (nonatomic, strong) NSArray *tabbarArray;

@property (nonatomic, strong) SFSafariViewController *safariVC;
@end

@implementation MainTabBarVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupVC];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    static dispatch_once_t onceToken;
    
    @weakify(self);
    dispatch_once(&onceToken, ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            @strongify(self);
            [self pushNotif];
            [self updateApp];
            [self channelTracking];
            [self appMark];
        });
    });
    
#ifndef IG_AppStore
    
    [self addTagLabel];
#else
    if ([UserManager sharedManager].user.role == UserRolesTypeAdmin) {
        [self addTagLabel];
    }
    
#endif
}

- (void)channelTracking {
    
    if (@available(iOS 10.0, *)) {
        
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        NSString *text = pasteboard.string;
        
        if (!text) return;
        
        NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
        if (!data) return;
        
        NSDictionary *params = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        if (!params|| params.count == 0 || ![params containsObjectForKey:@"chid"]) {
            return;
        }
        
        NSString *chid = params[@"chid"];
        
        if ([chid isKindOfClass:[NSNull class]]) {
            return;
        }
        
        NSMutableDictionary *daDict = [NSMutableDictionary dictionaryWithDictionary:@{@"lat":@([LocationManager sharedManager].currentLocation.coordinate.latitude),@"lng":@([LocationManager sharedManager].currentLocation.coordinate.longitude)}];
        
        [UserManager sharedManager].chid = params[@"chid"];
        
        [daDict setDictionary:params];
        
        [NetAPIManager postPhoneData:daDict];
        
        return;
    }
    
    SFSafariViewController *safari = [[SFSafariViewController alloc]initWithURL:[NSURL URLWithString:@"http://www.imguider.com/cookie.html"]];
    safari.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    safari.view.alpha = 0.1f;
    safari.view.userInteractionEnabled = NO;
    safari.view.backgroundColor = [UIColor whiteColor];
    
    safari.view.frame = CGRectMake([UIScreen mainScreen].bounds.size.width-1, [UIScreen mainScreen].bounds.size.height-1, 1, 1);
    
    [self addChildViewController:safari];
    [safari didMoveToParentViewController:self];
    [self.view insertSubview:safari.view atIndex:0];
    
    self.safariVC = safari;
    
    @weakify(self);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        @strongify(self);
        
        [self destroySafari];
    });
}


- (void)appMark {
    
    NSDate *insertDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"insertAppTime"];
    
    if (!insertDate) {
        return;
    }
    
    NSInteger differentTime = fabs([insertDate timeIntervalSinceNow]);
    
    if (differentTime < (3 * 24 * 60 * 60)) {
        return;
    }
    
    NSInteger times = [[NSUserDefaults standardUserDefaults] integerForKey:@"openTimes"];
    
    if (times % 3 != 0) {
        
        return;
    }
    if (@available(iOS 10.3, *)) {
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        [SKStoreReviewController requestReview];
        
        [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"insertAppTime"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        return;
    }
    
    [IGAlertView alertWithTitle:MYLocalizedString(@"HOMEPAGE_MARK_APP_TITLE", nil) message:MYLocalizedString(@"HOMEPAGE_MARK_APP_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"HOMEPAGE_MARK_APP_CANCEL", nil) commitBtn:MYLocalizedString(@"HOMEPAGE_MARK_APP_CONFORM", nil) commit:^{
        
        NSString *str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id1234141200?action=write-review"];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        
        [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"insertAppTime"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    } cancel:^{
        
        [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"insertAppTime"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }];
}

- (void)destroySafari {
    
    if(self.safariVC) {
        
        [self.safariVC willMoveToParentViewController:nil];
        [self.safariVC.view removeFromSuperview];
        [self.safariVC removeFromParentViewController];
        self.safariVC = nil;
    }
}

- (void)setupVC {
    
    HomePageVC *homePage = [IGUtil loadViewController:@"HomePageVC" storyboard:@"HomePage"];
    
    SelectDestinationVC *destination = [SelectDestinationVC new];
    
    UIViewController *orderVC = nil;
    
    if ([AppManager sharedManager].hasTicket) {
        
        orderVC = [AllOrderListVC new];
    } else {
        orderVC =[IGUtil loadViewController:@"AccountOrderListVC" storyboard:@"Account"];
    }
    
    MineVC *mine = [IGUtil loadViewController:@"MineVC" storyboard:@"Account"];
    
    NSArray *sourceArray = @[@{@"normal":@"首页-灰色",@"select":@"首页-蓝色",@"vc":homePage,@"title":MYLocalizedString(@"TABBAR_HOME", nil)},
                             @{@"normal":@"目的地-灰色",@"select":@"目的地-蓝色",@"vc":destination,@"title":MYLocalizedString(@"TABBAR_DESTINATION", nil)},
                             @{@"normal":@"订单-灰色",@"select":@"订单-蓝色",@"vc":orderVC,@"title":MYLocalizedString(@"TABBAR_ORDER", nil)},
                             @{@"normal":@"我的-灰色",@"select":@"我的-蓝色",@"vc":mine,@"title":MYLocalizedString(@"TABBAR_MINE", nil)}];
    
    
    [[UITabBarItem appearance]setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor clearColor],NSForegroundColorAttributeName,nil]forState:UIControlStateNormal];
    
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor clearColor],NSForegroundColorAttributeName,nil]forState:UIControlStateSelected];
    
    CGFloat width = kScreenWidth / sourceArray.count;
    CGFloat x = 0;
    
    NSMutableArray *tabbarArray = [NSMutableArray array];
    
    for (NSInteger i = 0; i < sourceArray.count; i ++) {
        
        NSDictionary *dict = sourceArray[i];
        
        UIViewController *vc = dict[@"vc"];
        vc.title = dict[@"title"];
        
        RTRootNavigationController *navVC = [[RTRootNavigationController alloc] initWithRootViewController:vc];
        
        [self addChildViewController:navVC];
        
        LinesTabBarItem *item = [[LinesTabBarItem alloc] initWithTitle:dict[@"title"] image:[UIImage imageNamed:dict[@"normal"]] selectedImage:[UIImage imageNamed:dict[@"select"]]];
        
        item.frame = CGRectMake(x, 0, width, kTableBarHeight - kBottomHeight);
        
        if (0 == i) {
            item.selected = YES;
        }
        
        [self.tabBar addSubview:item];
        [tabbarArray addObject:item];
        
        x += width;
    }
    
    self.tabbarArray = tabbarArray;
    
    self.delegate = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(screenShot) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushNotif) name:kRefreshMainVCNotif object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateApp) name:@"UpdateApp" object:nil];
    
    @weakify(self);
    [[AppManager sharedManager] addObserverBlockForKeyPath:@"lastCity" block:^(id  _Nonnull obj, id  _Nullable oldVal, id  _Nullable newVal) {
        
        @strongify(self);
        [self configDestionTabbarName];
        
    }];
    
    [self configDestionTabbarName];
}

- (void)pushNotif {
    
    Message *msg = [AppManager sharedManager].pushObj;
    
    if (!msg) {
        
        return;
    }
    
    NSString *title = msg.title;
    NSString *content = msg.content;
    NSString *type = msg.type;
    NSString *relationid = msg.relationid;
    
    [AppManager sharedManager].pushObj = nil;
    
    NSArray *detailArray = @[@"line",@"special",@"city",@"hot"];
    
    if ([detailArray containsObject:type]) {
        
        [self jumpDetailWithID:msg.relationid type:type];
        
        return;
    }
    
    
    if (title.length != 0 || content.length != 0) {
        
        return;
    }
    
    UIAlertController *alerVC = [UIAlertController alertControllerWithTitle:title message:content preferredStyle:UIAlertControllerStyleAlert];
    
    [alerVC addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) style:UIAlertActionStyleDefault handler:nil]];
    
    
    detailArray = @[@"answer",@"ticket",@"gotoweb"];
    
    if ([detailArray containsObject:type]) {
        
        [alerVC addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"PUBLIC_SHOW_DETAIL", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            if ([type isEqualToString:@"answer"]) {
                
                UIViewController *vc = [IGUtil loadViewController:@"AccountMyQuestion" storyboard:@"Account"];
                
                vc.hidesBottomBarWhenPushed = YES;
                [[IGUtil currentViewController].navigationController pushViewController:vc animated:YES];
                
            } else if ([type isEqualToString:@"ticket"]) {
                
                UIViewController *vc = [IGUtil loadViewController:@"AccountMyQuestion" storyboard:@"Account"];
                
                vc.hidesBottomBarWhenPushed = YES;
                [[IGUtil currentViewController].navigationController pushViewController:vc animated:YES];
                
            } else if ([type isEqualToString:@"gotoweb"]) {
                
                WebViewVC *webVC = [WebViewVC new];
                
                webVC.url = relationid;
                webVC.title = title;
                
                webVC.hidesBottomBarWhenPushed = YES;
                [[IGUtil currentViewController].navigationController pushViewController:webVC animated:YES];
            }
        }]];
    }
    
    [[IGUtil currentViewController] presentViewController:alerVC animated:YES completion:nil];
    
}


- (void)jumpDetailWithID:(NSString *)relationid type:(NSString *)type {
    
    
    UIViewController *vc = [IGUtil currentViewController];
    
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    if ([rootViewController presentedViewController]) {
        
        
        [vc dismissViewControllerAnimated:NO completion:^{
            
            [self jumpDetailWithID:relationid type:type];
        }];
        
        return;
    }
    
    if (self.selectedIndex == 1 && [IGUtil currentViewController].navigationController.viewControllers.count > 1) {
        
        [[IGUtil currentViewController].navigationController popToViewController:[IGUtil currentViewController].navigationController.viewControllers[1] animated:NO];
    } else {
        
        [[IGUtil currentViewController].navigationController popToRootViewControllerAnimated:NO];
    }
    
    //     线路
    if ([type isEqualToString:@"line"]) {
        
        
        LinePreDetailVC *detailVC = [IGUtil loadViewController:@"LinePreDetailVC" storyboard:@"LineDetail"];
        detailVC.lineid = relationid;
        detailVC.hidesBottomBarWhenPushed = YES;
        
        [[IGUtil currentViewController].navigationController pushViewController:detailVC animated:YES];
        
    } else if ([type isEqualToString:@"city"]) {
        
        CityVC *cityVC = [CityVC new];
        cityVC.cid = relationid;
        
        cityVC.hidesBottomBarWhenPushed = YES;
        [[IGUtil currentViewController].navigationController pushViewController:cityVC animated:YES];
        
    } else if ([type isEqualToString:@"hot"]) {
        
        CityTourListVC *vc = [CityTourListVC new];
        vc.isPopular = YES;
        vc.hidesBottomBarWhenPushed = YES;
        [[IGUtil currentViewController].navigationController pushViewController:vc animated:YES];
        
    } else {
        
        SpecialDetailVC * specialDetailVC = [[SpecialDetailVC alloc] init];
        
        specialDetailVC.specialid = relationid;
        
        specialDetailVC.hidesBottomBarWhenPushed = YES;
        
        [[IGUtil currentViewController].navigationController pushViewController:specialDetailVC animated:YES];
    }
}

//更新app
- (void)updateApp {
    
    NSString *appVersion = kVersion;
    NSString *netVersion = [AppManager sharedManager].version.version;
    NSString *minver = [AppManager sharedManager].version.minver;
    
    if ([appVersion compare:netVersion options:NSNumericSearch] == NSOrderedAscending) {
        NSString *msg = [NSString stringWithFormat:@"%@%@%@",appVersion,MYLocalizedString(@"PUBLIC_UPDATETO", nil),netVersion];
        
        if ([appVersion compare:minver options:NSNumericSearch] == NSOrderedAscending) {
            
            YYCForceUpdateVC *alertVC = [[YYCForceUpdateVC alloc] initWithTitle:MYLocalizedString(@"PUBLIC_UPDATE", nil) msg:msg btnTitle:MYLocalizedString(@"PUBLIC_UPDATE", nil) handel:^(NSString *ok) {
                
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/id1234141200"]];
            }];
            
            [alertVC showWithVC:self];
            
        } else {
            
            [IGAlertView alertWithTitle:MYLocalizedString(@"PUBLIC_UPDATE", nil) message:msg cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_UPDATE", nil) commit:^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/id1234141200"]];
                
            } cancel:nil];
        }
    }
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    
    [super setSelectedIndex:selectedIndex];
    
    [self reloadTabbarStatusWithIndex:selectedIndex];
}

- (void)configDestionTabbarName {
    
    LinesTabBarItem *item = self.tabbarArray[1];
    
    NSString *title = [AppManager sharedManager].lastCity.smartName ? [AppManager sharedManager].lastCity.smartName :MYLocalizedString(@"TABBAR_DESTINATION", nil);
    
    item.title = title;
}

- (void)reloadTabbarStatusWithIndex:(NSInteger)index {
    
    for (int i = 0; i < self.tabbarArray.count; i ++) {
        
        LinesTabBarItem *item = self.tabbarArray[i];
        
        if (i == index) {
            item.selected = YES;
        } else {
            
            item.selected = NO;
        }
    }
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)screenShot {
    
    [self popSheet];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.sl_popupController dismiss];
    });
}

#pragma mark - SnailSheetViewDelegate

- (void)sheetView:(SnailSheetView *)sheetView didSelectItemAtSection:(NSInteger)section index:(NSInteger)index {
    
    
    SnailSheetItemModel *model = [self sheetModels][section][index];
    
    self.sl_popupController.didDismiss = ^(SnailPopupController * _Nonnull popupController) {
        
        UIImage *image = [[UIApplication sharedApplication].keyWindow snapshotImage];
        
        [IGShare shareWebPageToPlatformType:model.platformType withURL:nil title:@"分享" descr:nil thumImage:image object:nil type:3 completion:nil];
    };
    
    [self.sl_popupController dismiss];
}

- (void)addTagLabel  {
    
    UILabel *tagLabel = [UILabel new];
    tagLabel.textColor = kThemeRedColor;
    tagLabel.text = [NSString stringWithFormat:@"%@ (version %@, build %@)",[[AppManager sharedManager].baseURLStr componentsSeparatedByString:@"."].firstObject, kVersion,kVersionBuild];
    tagLabel.font = Font(14);
    tagLabel.frame = CGRectMake(0, ISiPhoneX ? 30 : 10, kScreenWidth, 20);
    tagLabel.textAlignment = NSTextAlignmentCenter;
    [[UIApplication sharedApplication].keyWindow addSubview:tagLabel];
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    
    
    NSInteger index = [self.viewControllers indexOfObject:viewController];
    
    if (index == self.selectedIndex) {
        return YES;
    }
    
    if (index == 1) {
        
        RTRootNavigationController *nav = (RTRootNavigationController *)viewController;
        if ([AppManager sharedManager].lastCity && nav.viewControllers.count == 1) {
            
            CityVC *cityVC = [CityVC new];
            cityVC.cid = [AppManager sharedManager].lastCity.cid.stringValue;
            
            [nav pushViewController:cityVC animated:NO];
        }
    }
    
    RTContainerController *vc = (RTContainerController *)((RTRootNavigationController *)viewController).topViewController;
    
    if ([vc isKindOfClass:[RTContainerController class]]) {
        vc = vc.contentViewController;
    }
    
    
    if (index == 2) {
        
        if ([UserManager sharedManager].token) {
            
            [self reloadTabbarStatusWithIndex:index];
            return YES;
        }
        
        LoginVC *loginVC = [LoginVC new];
        loginVC.delegate = self;
        RTRootNavigationController *nav = [[RTRootNavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:nav animated:YES completion:nil];
        
        return NO;
    }
    
    [self reloadTabbarStatusWithIndex:index];
    
    return YES;
}

- (void)loginSuccess {
    
    self.selectedIndex = 2;
}


@end

